// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import './utils/extend'
import './utils/log'
import Vue from 'vue'
import { mapGetters } from 'vuex'
import VueRouter from 'vue-router'
import MintUi from 'mint-ui'
import VueAwesomeSwiper from 'vue-awesome-swiper'

import routes from './common/route.js'
import store from './store'
import App from './App'
import { getUrlParam, Reporter } from './common/util'
import { LoadScene } from './utils/enum'

import { WxShare } from './common/api/wxShare'
import { LoginAuto } from "./common/api/user";
// import { GroupList } from './common/api/cart'

const DATA_REPORT = process.env.DATA_REPORT === 'yes'
const ISDEBUG = process.env.NODE_ENV !== 'production'

const ls = window.localStorage
const dom = window.document
const body = dom.querySelector('body')
const shellsClass = ['waiting-home', 'waiting-product']

/**
 * 数据统计上报
 * @param {String} name 事件名
 * @param {String} label 事件子分类
 * @param {Object} kv 事件的参数信息，描绘发生事件时的属性和场景
 */
const report = (name, label = '', kv = null) => {
  if (!name) {
    console.error('数据上报参数异常：事件名不可为空')
    return
  }
  // if (window.TDAPP) {
  // if (window.MtaH5 || window._hmt) {
  if (window._hmt) {
    console.log('  report. ', 'name:', name, ',label:', label, ',kv:', kv)
    // window.TDAPP.onEvent(name, label, kv)

    let param = { label, ...(kv || {}) }

    // window.MtaH5 && window.MtaH5.clickStat(name, param)

    // _hmt.push(['_trackEvent', category, action, opt_label, opt_value]);
    // window._hmt && window._hmt.push(['_trackEvent', name, 'event', JSON.stringify(param)])
    window._hmt.push(['_trackEvent', name, 'event', JSON.stringify(param)])
  } // else console.info('  no reporter,ignore. ', 'name:', name, ',label:', label, ',kv:', kv)
}

/**
 * 腾讯mta统计上报
 * @param {String} eventid 事件id
 * @param {Object?} param 事件参数
 */
const mtaReport = (eventid, param) => {
  // console.log('  mta report', eventid, param)
  if (window.MtaH5) window.MtaH5.clickStat(eventid, param)
}

// Set this to false to prevent the production tip on Vue startup.
Vue.config.productionTip = false

Vue.use(VueRouter)
Vue.use(MintUi)
Vue.use(VueAwesomeSwiper)

// console.log(JSON.parse(ls.getItem('currentUser')).token)
const router = new VueRouter({
  mode: 'history', routes,
  scrollBehavior(to, from, savedPosition) {
    if (savedPosition) {
      return new Promise((resolve, reject) => {
        setTimeout(() => {
          resolve(savedPosition)
        }, 300)
      })
    } else return { x: 0, y: 0 }
  }
})
router.beforeEach((to, from, next) => {
  window._from = from.fullPath

  let cName = to.meta.shell || ''
  if (cName) body.classList.add(cName)
  else body.classList.remove(...shellsClass)

  let wss = window.sessionStorage
  let launchKey = 'FC_LAUNCHED'
  if ((to.path === '/' || to.path == '/loadApp') && !(/Android|webOS|iPhone|iPod|BlackBerry/i.test(navigator.userAgent))) {
    next('/downApp')
    return
  }
  if (to.path == '/downApp' && (/Android|webOS|iPhone|iPod|BlackBerry/i.test(navigator.userAgent))) {
    next('/loadApp')
    return
  }
  if (to.path === '/' && !wss.getItem(launchKey)) {
    wss.setItem(launchKey, true)
    next('/launch')
    return
  }
  if (!wss.getItem(launchKey)) wss.setItem(launchKey, true)

  if (to.meta.requireAuth) {
    // 判断该路由是否需要登录权限
    if (JSON.parse(ls.getItem('currentUser') || '{}').token) {
      // 通过vuex state获取当前的token是否存在
      // alert('存在');
      next()
    } else {
      // ls.removeItem('currentUser')
      // alert('不存在');
      store.dispatch('setUserInfo', {})
      next('/login')
      // if (vm && vm.ISWX) {
      //   next({
      //     path: '/wxlogin'
      //   })
      // } else {
      //   next({
      //     path: '/login'
      //   })
      // }
    }
  } else next()
})
router.afterEach(route => {
  setTimeout(() => {
    $log({ e: $log.event.pv, p: location.search })
  }, 300);

  // if (route.meta.shell) vm.$nextTick(() => { body.classList.remove(...shellsClass) })
  report('页面访问/路由切换', window.location.origin + route.fullPath)

  MintUi.MessageBox.close()
})

/* 全局通用模版 */
Vue.component('v-back', {
  template: `<div class="nav-back flex-center" @click.stop.prevent="navBack"><div v-if='!hide'><span class="ico-back"></span></div></div>`,
  data() {
    return {
      hide: false
    }
  },
  props: {
    returnBack: { type: Number }
  },
  methods: {
    navBack() {
      if (this.hide) return
      if (this.returnBack) {
        this.$router.push('/user/home')
        return
      }
      if (window.history.length < 2) {
        this.$router.push('/')
      } else this.$router.go(-1) // 单独进入时后退到首页
    }
  }
})

// 获取焦点
Vue.directive('focus', function (el, { value }) {
  if (value) {
    el.focus()
  }
})

Vue.component('v-cart', {
  template: `<div class="nav-cart flex-center" @click.stop.prevent='gotoCart()'>
   <div :class="{cartimg_box:cartList.length>0}"><img :src="cartImg" alt=""></div></div>`, // 购物车列表有 cartimg_box img外层div加calss
  props: {
    isshow: { type: Boolean, default: false },
    isdark: { type: Boolean, default: true }
  },
  computed: {
    cartImg() {
      // return this.isdark ? require('./assets/img/cart.png') : require('./assets/img/cart_light.png')
      return this.isdark ? '//files.eyee.com/mcdn/static/img/cart.png' : '//files.eyee.com/mcdn/static/img/cart_light.png'
    },
    ...mapGetters({ cartList: 'cartList' })
  },
  methods: {
    // getCartList() {
    //   GroupList()
    //     .then(res => {
    //       if (res) {
    //         res = res.map(data => {
    //           data.count = 0
    //           data.checked = false
    //           data.disable = true
    //           data.allPay = 0
    //           data.cartEdit = true
    //           data.items = data.items.map(i => {
    //             i.checked = false
    //             if (i.specialprice > 0) {
    //               i.pay = i.count * i.specialprice
    //             } else {
    //               i.pay = i.count * i.saleprice
    //             }
    //             return i
    //           })
    //           return data
    //         })
    //         this.cartLists = res
    //         this.$store.dispatch('setCartList', res)
    //       } else {
    //         this.$store.dispatch('setCartList', [])
    //       }
    //     })
    //     .catch(e => {
    //       this.hasdata = 1
    //       console.log(e && e.msg ? e.msg : 'error:' + e)
    //     })
    // },
    gotoCart() {
      if (this.$route.name === 'product-detail') mtaReport('spxq_gouwuche_dj')
      if (ls.getItem('currentUser') && JSON.parse(ls.getItem('currentUser')).token !== '') {
        this.$router.push('/cart')
      } else {
        this.$router.push('/login')
        // if (vm.ISWX) {
        //   this.$router.push('/wxlogin')
        // } else {
        //   this.$router.push('/login')
        // }
      }
    }
  } // ,
  // mounted() {
  //   this.getCartList()
  // }
})

Vue.component('v-header', {
  template: `<header v-if='!hide' ref='header' class="flex nav-top" :class="'nav-top-' + bg" >
  <v-back v-if="showback" :returnBack="returnBack"></v-back>
  <slot></slot></header>`,
  props: {
    showback: { type: Boolean, default: true },
    bg: { type: String, default: 'light' },
    hasgap: { type: Boolean, default: true },
    returnBack: { tyoe: Number }
  },
  data() {
    return {
      hide: false
    }
  },
  mounted() {
    this.$nextTick(function () {
      if (this.hasgap === true && !this.hide) {
        this.$parent.$el.style.marginTop = this.$el.clientHeight + 'px'
      } else {
        this.$parent.$el.style.marginTop = 0
      }
    })

    // this.$refs.header.parentElement.style.marginTop = '48px';:top-method="reload"
  }
})

Vue.component('v-list', {
  template: `<mt-loadmore ref="loadmore" v-infinite-scroll="loadmore" infinite-scroll-disabled="isend" infinite-scroll-distance="50"
  infinite-scroll-immediate-check="false" :auto-fill="false" :top-method="reload" >

      <!-- :bottom-method="loadmore" :bottom-all-loaded="isend"  :bottom-pull-text="'加载更多'" :bottom-drop-text="'释放加载'"-->
     <div class="clearfix"><slot></slot></div>
     <p class='no-more' v-show="isend">哼，我是有底线的~~</p>
     <p class='load-more' :class='{act:moreHandling}' v-show='!isend'><span>努力加载中</span></p>
    </mt-loadmore>`,
  props: {
    loadHandle: { type: Function },
    moreHandle: { type: Function, default: () => { } },
    isend: { type: Boolean, default: false },
    moreHandling: { type: Boolean, default: false }
  },
  methods: {
    reload() {
      this.loadHandle(this.$refs.loadmore)
      this.$refs.loadmore.onTopLoaded()
    },
    loadmore() {
      if (this.moreHandling === true) return false
      this.moreHandle(this.$refs.loadmore)
      this.$refs.loadmore.onBottomLoaded()
    }
  }
})

Vue.component('v-error', {
  template: `<div class="error-req flex-center" @click.stop="reload">
    <img :src="img" alt="">
    <p>请求失败啦~~</p>
    <p>休息一下~~~点击空白处再试试</p>
    <a href="javascript:;" @click.stop.prevent="go">随处逛逛</a>
  </div>`,
  data() {
    return {
      img: '//files.eyee.com/mcdn/static/img/error_req.png' // require('./assets/img/error_req.png')
    }
  },
  computed: {
    goUrl() {
      let routes = ['/news', '/', '/mall/shop', '/', '/mall/limit', '/brand', '/mall/ghost']
      let rand = 0
      let now = Date.now()
      rand = now % routes.length
      // console.log('rand',rand);
      return routes[rand]
    }
  },
  methods: {
    reload() {
      window.location.reload()
    },
    go() {
      this.$router.replace(this.goUrl)
    }
  }
})
Vue.component('v-cutlist', {
  template: `<mt-loadmore ref="loadmore" v-infinite-scroll="loadmore" infinite-scroll-disabled="isend" infinite-scroll-distance="50"
  infinite-scroll-immediate-check="false" :auto-fill="false">

      <!-- :bottom-method="loadmore" :bottom-all-loaded="isend"  :bottom-pull-text="'加载更多'" :bottom-drop-text="'释放加载'"-->
     <div class="clearfix"><slot></slot></div>
     <p class='no-more' v-show="isend">哼，我是有底线的~~</p>
     <p class='load-more' :class='{act:moreHandling}' v-show='!isend'><span>努力加载中</span></p>
    </mt-loadmore>`,
  props: {
    loadHandle: { type: Function },
    moreHandle: { type: Function, default: () => { } },
    isend: { type: Boolean, default: false },
    moreHandling: { type: Boolean, default: false }
  },
  methods: {
    reload() {
      this.loadHandle(this.$refs.loadmore)
      this.$refs.loadmore.onTopLoaded()
    },
    loadmore() {
      if (this.moreHandling === true) return false
      this.moreHandle(this.$refs.loadmore)
      this.$refs.loadmore.onBottomLoaded()
    }
  }
})
Vue.component('v-server', {
  template: `<div class="nav-server flex-center" @click='click'>
  <img :src="serverImg" alt=""></div>`,
  props: {
    isShow: { type: Boolean, default: false },
    click: Function
  },
  computed: {
    serverImg() {
      return '//files.eyee.com/mcdn/static/img/service.png' // require('./assets/img/service.png')
    }
  }
})
/*
* 延迟渲染模版
* delay:Number,延迟时间(单位毫秒),最小/默认为30ms
* loaded:Function,渲染结束后的回调函数
*/
Vue.component('v-delay', {
  template: `<div><slot v-if="show"></slot></div>`,
  props: {
    delay: {
      type: Number,
      default() {
        return 30
      }
    }
  },
  data() {
    return {
      show: true
    }
  },
  created() {
    // console.log('v-delay', this.delay)
    this.delayShow()
  },
  methods: {
    delayShow() {
      this.show = false
      let delay = this.delay
      delay = delay < 30 ? 30 : delay
      setTimeout(() => {
        this.show = true
        this.$emit('loaded')
      }, delay)
    }
  }
})

/*
** 如果h5页面在APP中，h5跳转到APP;否则，跳转相关h5页面
*/
const setupWebViewJavascriptBridge = callback => {
  if (window.WebViewJavascriptBridge) {
    return callback(WebViewJavascriptBridge)
  } else {
    dom.addEventListener('WebViewJavascriptBridgeReady', function () {
      callback(WebViewJavascriptBridge)
    }, false)
  }
  if (window.WVJBCallbacks) {
    return window.WVJBCallbacks.push(callback)
  }
  window.WVJBCallbacks = [callback]
  var WVJBIframe = dom.createElement('iframe')
  WVJBIframe.style.display = 'none'
  WVJBIframe.src = 'wvjbscheme://__BRIDGE_LOADED__'
  dom.documentElement.appendChild(WVJBIframe)
  setTimeout(function () {
    dom.documentElement.removeChild(WVJBIframe)
  }, 0)
}
Vue.directive('web-app', {
  bind: (el, binding, vnode) => {
    setupWebViewJavascriptBridge(function (bridge) {
      // 调试
      var uniqueId = 1
      function log(message, data) {
        var log = dom.getElementById('log')
        var el = dom.createElement('div')
        el.className = 'logLine'
        el.innerHTML = uniqueId++ + '. ' + message + ':<br/>' + JSON.stringify(data)
        if (log.children.length) { log.insertBefore(el, log.children[0]) } else { log.appendChild(el) }
      }
      console.log('vm.share 页面分享信息: ', vm.share, vnode.context.share)

      if (vnode.context && vnode.context.share) {
        vm.share.desc = vnode.context.share.desc
        vm.share.title = vnode.context.share.title
        vm.share.link = vnode.context.share.link
        vm.share.imgUrl = vnode.context.share.imgUrl
      }
      if (vm.ISAPP) {
        bridge.callHandler('getAppActivityShareContent', {
          'sharecontent': vm.share.desc,
          'sharetitle': vm.share.title,
          'shareurl': vm.share.link,
          'sharepicurl': vm.share.imgUrl,
          'callbackname': ''
        }, function (response) { })
      }

      // el.addEventListener('touchend', function(event) {
      el.onclick = function () {
        let elData = binding.value
        console.log('web-app directive bindingValue', elData)
        // '点击>>'
        if (elData.urlExist) {
          if (vm.ISAPP && elData.urltype.paramstype != 11) {
            console.log('APP 列表: ', elData.urltype.appUrl.name, elData.urltype.appUrl.params)
            // 'app内嵌点击>>appUrl.name:' + JSON.stringify(appUrl.name) + 'appUrl.params' + JSON.stringify(appUrl.params)
            bridge.callHandler(elData.urltype.appUrl.name, elData.urltype.appUrl.params, function (response) {
              console.log('Call bridge response: ', response)
            })
          } else {
            let routePath = elData.urltype.webUrl.name
            let paramId = elData.urltype.webUrl.params.id
            // console.log(routePath, elData.urltype.webUrl.params)
            if (elData.urltype.webUrl.params.type == 'brand') {
              var set = {}
              // set.brandid = paramId
              set.brandid = paramId
              vm.$store.dispatch('confirOption', { data: set })
              routePath = `${routePath}${routePath.indexOf('?') > -1 ? '&' : '?'}brandid=${paramId}`
              vm.$router.push(routePath)
            } else if (elData.urltype.webUrl.params.type == 'category') {
              var set = {}
              // set.brandid = paramId
              set.categoryid = paramId
              vm.$store.dispatch('confirOption', { data: set })
              routePath = `${routePath}${routePath.indexOf('?') > -1 ? '&' : '?'}categoryid=${paramId}`
              vm.$router.push(routePath)
            } else if (elData.urltype.webUrl.params.categoryname) {
              vm.$router.push(routePath + elData.urltype.webUrl.params.categoryname + '/' + paramId)
            } else {
              if (paramId) {
                let url = routePath + paramId
                vm.$router.push(url)
              } else {
                vm.$router.push(routePath)
              }
            }
          }
        }
      }
    })
    function setupWebViewJavascriptBridge(callback) {
      if (vm.ISAPP) {
        // app内嵌
        if (window.WebViewJavascriptBridge) {
          return callback(WebViewJavascriptBridge)
        } else {
          dom.addEventListener('WebViewJavascriptBridgeReady', function () {
            callback(WebViewJavascriptBridge)
          }, false)
        }
        if (window.WVJBCallbacks) {
          return window.WVJBCallbacks.push(callback)
        }
        window.WVJBCallbacks = [callback]
        var WVJBIframe = dom.createElement('iframe')
        WVJBIframe.style.display = 'none'
        WVJBIframe.src = 'wvjbscheme://__BRIDGE_LOADED__'
        dom.documentElement.appendChild(WVJBIframe)
        setTimeout(function () {
          dom.documentElement.removeChild(WVJBIframe)
        }, 0)
      } else {
        // 非app内嵌
        callback()
      }
    }
  }
})

/*
* 过滤器 --- 图集返回一张
*/
Vue.filter('firstImg', function (image) {
  return (image || '').split('|')[0]
  // if (image) {
  //   let suffix = '!w650'
  //   image = image.split('|')[0]
  //   if (image.indexOf(suffix) < 0) image = image + '!w650'
  //   return image
  // }
})
Vue.filter('https', function (val) {
  if (val) {
    let rgx = /http:\/\/files\.eyee\.com(?!\.(jpg|png|gif|jpeg)).+?\.(jpg|png|gif|jpeg)/gi
    return val.replace(rgx, function (match) {
      return match.replace('http://', 'https://')
    })
  } else return val
})

/* 十进制补零 */
Vue.filter('decpadleft', val => {
  if (val < 10) return '0' + val
  else return val
})
// 保留两位小数
Vue.filter('tofixed', val => {
  if (val != null && val !== undefined && val >= 0) {
    return parseFloat(val).toFixed(2)
  }
})
// 手机中间四位显示星星
Vue.filter('phonestar', val => {
  if (val) {
    var mobile = val.split('-')[1].substr(3, 5)
    return val.split('-')[1].replace(mobile, '*****')
  }
})
/* 全局混合 */
Vue.mixin({
  methods: {
    loading(text = '加载中···') {
      let loader = MintUi.Indicator
      loader.open({
        text,
        spinnerType: 'triple-bounce' // 'snake''fading-circle''double-bounce''triple-bounce'
      })
      return loader
    },
    setToolBar({ title, bgcolor, textcolor, showshoppingcarticon }) {
      dom.title = title
      let _ = this
      if (_.$root.ISAPP) {
        let params = {}
        if (title) params.title = title
        if (bgcolor) params.bgcolor = bgcolor
        if (textcolor) params.textcolor = textcolor
        params.showshoppingcarticon = !!showshoppingcarticon

        // console.log('javascriptBridge setAppToolbar: ', params)
        _.javascriptBridge({
          name: "setAppToolbar", params
        });
      }
    },
    getQueryParamUser(params) {
      let _ = this, queryParam = params || getUrlParam("param");
      // APP进入时先清空登录态再重新通过链接参数自动登录, 防止更换账号未同步更换
      return new Promise((resolve, reject) => {
        if (_.$root.ISAPP) {
          // 链接参数登录处理
          if (queryParam) {
            try {
              let param = JSON.parse(decodeURIComponent(queryParam)),
                user = _.user || {};
              if (param.token && (!user.token || user.token != param.token)) {
                _.$store.dispatch("setUserInfo", {});
                LoginAuto(param)
                  .then(res => {
                    _.$store.dispatch("setUserInfo", res);
                    resolve({ param, user: res })
                  })
                  .catch(e => {
                    console.error("链接参数自动登录异常: ", e);
                    reject({ code: 3, param, e })
                  });
              } else resolve({ param, user: store.getters.userInfo })
            } catch (e) {
              console.error("deal url query param error: ", e);
              reject({ code: 2, query: queryParam, e })
            }
          } else reject({ code: 1 })
        } else reject({ code: 0 })
      })
    },
    getCurrentUser() {
      if (this.$root.ISAPP && getUrlParam('param')) {
        let param = getUrlParam('param')

        let tempParam = null
        try {
          tempParam = JSON.parse(decodeURIComponent(param))
        } catch (e) {
          console.log('JSON parse error: ', e)
        }
        if (tempParam) {
          this.currentUser = tempParam
          window.localStorage.setItem('distributionId', tempParam.distributionId)
          this.$store.dispatch('setUserInfo', tempParam)
        }
      } else {
        let tempUser = null
        try {
          tempUser = JSON.parse(window.localStorage.getItem('currentUser') || '{}')
        } catch (e) {
          console.log('JSON parse error: ', e)
        }
        this.currentUser = tempUser
        this.currentUser.distributionId = window.localStorage.getItem('distributionId')
      }
      console.log('Mixin currentUser: ', this.currentUser)

      return this.currentUser
    },
    report,
    mtaReport,
    javascriptBridge(val) {
      console.log('    javascriptBridge: ', val.name, val.params)
      // console.log('bridge step1: ', val)
      setupWebViewJavascriptBridge(function (bridge) {
        // console.log('bridge step2: ', val)
        bridge.callHandler(val.name, val.params,
          function (response) { console.log('bridge response: ', response) })
      })
    },
    /**
     * 兼容qzone的跳转
     * @param {String} path 跳转路径
     * @param {String} type 跳转方式，仅使用自带路由时有效，同 路由跳转方式
     */
    qzoneGo(path, type = 'push') { // , route = false
      this.$router[type](path)
    },
    https(val) {
      if (val) {
        let rgx = /http:\/\/(files|api)\.eyee\.com(?!\.(jpg|png|gif|jpeg)).+?\.(jpg|png|gif|jpeg)/gi
        return val.replace(rgx, function (match) {
          return match.replace('http://', 'https://')
        })
      } else return val
    },

    /*
     * 提示
     * msg:String,必须,提示内容
     * icon:String,可无,自定义icon图标类名,若传值则提示位于屏幕中心
     */
    toast(msg, icon = '') {
      let data = { message: msg, position: 'middle', duration: 3000 }
      if (icon && icon.length > 0) {
        data.iconClass = icon
        data.position = 'middle'
      }
      MintUi.Toast(data)
    },
    /*
    * 警示框
    * msg:String,必须,内容
    * callback:Function,可无,关闭的回调函数
    */
    alert(msg, callback = function () { }) {
      MintUi.MessageBox.alert(msg).then(action => {
        callback(action)
      })
    },
    popup({ title = '提示信息', msg, showCancelButton = true }) {
      let data = {
        title: title,
        message: msg,
        showCancelButton: false
      }
      MintUi.MessageBox(data)
    },
    /*
    * 确认提示框
    * 以对象形式传参
    * msg:String,必须,确认提示信息
    * okText:String,可无,确认按钮文本,默认为'确定'
    * cancelText:String,可无取消按钮文本,默认为'取消'
    * ok:Function,可无,确认操作后的回调函数
    * cancel:Function,可无,取消操作后的回调函数
    */
    confirm({ msg, confirmButtonClass = '', cancelButtonClass = '', title = '确认提示', okText = '确定', cancelText = '取消', ok = () => { }, cancel = () => { } }) {
      let data = {
        title: title,
        message: msg,
        confirmButtonText: okText,
        showCancelButton: true,
        cancelButtonText: cancelText,
        confirmButtonClass: confirmButtonClass,
        cancelButtonClass: cancelButtonClass,
        closeOnClickModal: false
      }
      MintUi.MessageBox(data).then(action => {
        if (action === 'confirm') ok()
        else cancel()
      })
    },
    /*
    * 初始化分享
    * sharetype 分享类型 0资讯，1商城，2其他，不传默认2
    * info 分享数据 {title:分享标题,desc:分享描述,img:分享图标/图片}
    */
    initShare({ sharetype = 2, info = {}} = {}) {
      let _ = this
      console.log('分享的数据：' + JSON.stringify(info))
      if (_.$root.ISWX) {
        let url = info.url || window.location.href
        let share = {
          title: info.title || '',
          desc: info.desc || '',
          link: url,
          imgUrl: info.img || ''
        }

        let defaultShare = store.getters.baseValue.shareinfos
        let metaDesc = dom.querySelector('meta[name=description]')
        defaultShare = defaultShare && defaultShare[sharetype]
        if (sharetype === 2) {

        } else {
          console.log('资讯或商城分享', defaultShare)
          if (defaultShare) {
            if (!share.title) share.title = defaultShare.title
            if (!share.desc) share.desc = defaultShare.content
            if (!share.imgUrl) share.imgUrl = defaultShare.icon
          }
        }
        if (!share.title) share.title = dom.title
        if (!share.desc) share.desc = metaDesc && metaDesc.content
        if (!share.imgUrl) share.imgUrl = 'https://files.eyee.com/EYEE/icons/sharelogo.png'

        let result = WxShare(share, store)
        result === false ? console.error('分享初始化失败了') : console.log('初始化分享--', share)
      }
    },

    /*
    * 跳转下载app
    * type === -1 时 为缺省功能提示前往APP的弹框
    */
    loadApp(type) {
      // console.log('跳转下载app', type)
      let option
      if (type === -1) {
        option = {
          title: '',
          msg: '我还在完善中，前往 斗牛APP 操作吧~',
          cancelText: '知道了~',
          okText: '立即前往',
          ok: () => {
            this.sceneLoad()
            // window.open('http://a.app.qq.com/o/simple.jsp?pkgname=com.etechs.eyee', '_blank');
          }
        }
      } else {
        option = {
          msg: '立即跳转至斗牛APP ?',
          okText: '跳转',
          ok: () => {
            this.openAppClient(type)
            // window.open('http://a.app.qq.com/o/simple.jsp?pkgname=com.etechs.eyee', '_blank');
          }
        }
      }
      this.confirm(option)
    },
    sceneLoad(scene) {
      let appStore = 'https://itunes.apple.com/cn/app/eyee/id962223967?mt=8'
      let loadLink = 'https://gio.ren/oVxWLoO' // http://a.app.qq.com/o/simple.jsp?pkgname=com.etechs.eyee
      let wxLoadLink = 'https://gio.ren/oVxWLoO'

      switch (scene) {
        case LoadScene.newUserHelp:
          appStore = 'https://gio.ren/rBDmJM1'
          loadLink = 'https://gio.ren/r3Mmv1Y'
          wxLoadLink = 'https://gio.ren/o3p99rd'
          break;
      }

      if (this.$root.ISIOS) window.location = appStore
      else if (this.$root.ISWX) window.location = wxLoadLink
      else window.open(loadLink, '_blank')
    },
    /*
    * 打开APP 或跳转到下载APP页面
    */
    openAppClient(type) {
      const nv = window.navigator
      let _ = this, { path, params, name, query } = _.$route
      // console.log(type)
      // console.log(this.$route.path)
      var pagetype = ''
      let productid, oshoppid, articleid, articletype, brandid, itemid, brandname, categoryname, seriesid, shoeid
      var jsonPara
      var config = {
        /* scheme:必须*/
        scheme_IOS: 'eyee://eyee/h5?paramter=',
        timeout: 600
      }
      // 浏览器所有版本信息
      var browser = {
        versions: (function () {
          let u = nv.userAgent
          // let app = nv.appVersion
          return {
            // 移动终端浏览器版本信息
            trident: u.indexOf('Trident') > -1, // IE内核
            presto: u.indexOf('Presto') > -1, // opera内核
            webKit: u.indexOf('AppleWebKit') > -1, // 苹果、谷歌内核
            gecko: u.indexOf('Gecko') > -1 && u.indexOf('KHTML') === -1, // 火狐内核
            mobile: !!u.match(/AppleWebKit.*Mobile.*/), // 是否为移动终端
            ios: !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/), // ios终端
            android: u.indexOf('Android') > -1 || u.indexOf('Linux') > -1, // android终端或uc浏览器
            iPhone: u.indexOf('iPhone') > -1, // 是否为iPhone或者QQHD浏览器
            iPad: u.indexOf('iPad') > -1, // 是否iPad
            webApp: u.indexOf('Safari') === -1, // 是否web应该程序，没有头部与底部
            eyee: u.indexOf('platform/app') !== -1
          }
        })(),
        language: (nv.browserLanguage || nv.language).toLowerCase()
      }

      let appStore = 'https://itunes.apple.com/cn/app/eyee/id962223967?mt=8'
      let loadLink = 'https://gio.ren/oVxWLoO' // http://a.app.qq.com/o/simple.jsp?pkgname=com.etechs.eyee

      // APP内直接跳转下载
      if (browser.versions.eyee) {
        window.location.href = browser.versions.ios ? appStore : loadLink
        return
      }

      if (path.indexOf('/mall/limit') >= 0) {
        pagetype = 2
        console.log('limit')
      } else if (path.indexOf('/productDetail') >= 0) {
        pagetype = 3
        productid = params.id
        console.log('productDetail')
      } else if (path.indexOf('/shop/shopdetail') >= 0) {
        pagetype = 4
        oshoppid = params.id
        console.log('shopdetail')
      } else if (path.indexOf('/ghost') >= 0) {
        pagetype = 5
        console.log('ghost')
      } else if (path.indexOf('/news/detail') >= 0) {
        pagetype = 8
        articletype = type
        articleid = params.id
        console.log('articledetl')
      } else if (path.indexOf('/news/picrecomd/') >= 0) {
        pagetype = 8
        articletype = 1
        articleid = params.id
        console.log('picrecomd')
      } else if (path.indexOf('brand') >= 0) {
        if (name.indexOf('brandstore') >= 0) {
          pagetype = 10
          console.log('brandlist')
        }
      } else if (path.indexOf('/brandInfo/') >= 0) {
        pagetype = 11
        brandid = params.id
        console.log('brandinfo')
      } else if (path.indexOf('/BrandDetail/') >= 0) {
        pagetype = 12
        itemid = params.id
        brandname = query.name
        console.log('branditeminfo')
      } else if (path.indexOf('/sneakerSeries/') >= 0) {
        pagetype = 13
        categoryname = params.catyname
        seriesid = params.seriesid
      } else if (path.indexOf('/sneakerDetail/') >= 0) {
        pagetype = 14
        shoeid = params.shoeid
      } else if (path.indexOf('/coupon') >= 0) {
        pagetype = 16
        console.log(pagetype)
      }
      switch (pagetype) {
        // 限量发售页
        case 2:
          jsonPara = '{"pagetype":' + pagetype + '}'
          break
        // 商品详情页
        case 3:
          jsonPara = '{"productid":"' + productid + '","pagetype":' + pagetype + '}'
          break
        // 店铺详情
        case 4:
          jsonPara = '{"shopid":"' + oshoppid + '","pagetype":' + pagetype + '}'
          break
        // 鬼市
        case 5:
          jsonPara = '{"pagetype":' + pagetype + '}'
          break
        // 资讯详情
        case 8:
          jsonPara = '{"articleid":"' + articleid + '","pagetype":' + pagetype + ',"articletype":' + articletype + '}'
          break
        // 品牌库列表页
        case 10:
          jsonPara = '{"pagetype":' + pagetype + '}'
          break
        // 品牌库二级详情
        case 11:
          jsonPara = '{"brandid":"' + brandid + '","pagetype":' + pagetype + '}'
          break
        // 品牌库三级子详情
        case 12:
          jsonPara = '{"itemid":"' + itemid + '","pagetype":' + pagetype + ',"brandname":' + brandname + '}'
          break
        // 潮鞋专区系列页面
        case 13:
          jsonPara = '{"categoryname":"' + categoryname + '","pagetype":' + pagetype + ',"seriesid":' + seriesid + '}'
          break
        // 潮鞋专区详情页面
        case 14:
          jsonPara = '{"shoeid":"' + shoeid + '","pagetype":' + pagetype + '}'
          break
        // 优惠券列表页
        case 16:
          jsonPara = '{"pagetype":' + pagetype + '}'
          break
      }
      var ifr = dom.createElement('iframe')
      ifr.style.display = 'none'
      dom.body.appendChild(ifr)
      // console.log(jsonPara)
      ifr.src = config.scheme_IOS + jsonPara

      // 判断系统浏览器
      var loadDateTime = new Date()
      setTimeout(function () {
        var timeOutDateTime = new Date()
        if (timeOutDateTime - loadDateTime < 5000) {
          if (browser.versions.mobile) {
            // 判断是否是移动设备打开。browser代码在下面
            var uaa = nv.userAgent.toLowerCase() // 获取判断用的对象
            if (browser.versions.ios) {
              if (/micromessenger/.test(uaa)) {
                // _.downloadPage = true;
                window.open(appStore, '_blank') // 'http://a.app.qq.com/o/simple.jsp?pkgname=com.etechs.eyee'
              } else if (uaa.match(/QQ/i) == 'qq') {
                setTimeout(function () {
                  window.location = appStore // 'https://itunes.apple.com/cn/app/eyee/id962223967?mt=8'
                }, 10)
              } else {
                setTimeout(function () {
                  window.location = appStore // 'https://itunes.apple.com/cn/app/eyee/id962223967?mt=8'
                }, 10)
              }
            } else if (browser.versions.android) {
              var state = null
              if (/micromessenger/.test(uaa)) {
                // _.downloadPage = true;
                window.open(loadLink, '_blank') // 'http://a.app.qq.com/o/simple.jsp?pkgname=com.etechs.eyee'
              } else if (uaa.match(/QQ/i) == 'qq') {
                state = null
                try {
                  state = window.open(loadLink, '_blank') // 'http://a.app.qq.com/o/simple.jsp?pkgname=com.etechs.eyee'
                } catch (e) {
                }
                if (state) {
                  window.close()
                } else {
                  window.location = config.scheme_IOS + jsonPara
                }
              } else {
                state = null
                try {
                  state = window.open(loadLink, '_blank') // 'http://a.app.qq.com/o/simple.jsp?pkgname=com.etechs.eyee'
                } catch (e) {
                }
                if (state) {
                  window.close()
                } else {
                  window.location = config.scheme_IOS + jsonPara
                }
              }
            }
          }
        } else {
          window.close()
        }
      }, 500)
      window.location = config.scheme_IOS + jsonPara
    }
  }
})
/* 滚动监听指令*/
let scrollHandle
Vue.directive('scroll', {
  bind: (el, binding) => {
    let handle = binding.value
    if (typeof handle === 'function') {
      window.addEventListener('scroll', (scrollHandle = () => {
        handle()
      })
      )
    }
  },
  unbind: (el, binding) => {
    window.removeEventListener('scroll', scrollHandle)
    scrollHandle = null
  }
})

/* eslint-disable no-new */
const vm = new Vue({
  el: '#app',
  router,
  store,
  template: '<App/>',
  components: { App },
  data: {
    downloadPage: false,
    ISAPP: false, // 判断是否在APP中打开h5页面
    ISIOS: false, // 判断移动端是否为ios
    ISWX: false, // 判断是否在微信中
    ISOpenBee: true,
    isdebug: ISDEBUG,
    share: {
      title: '', // 分享标题
      desc: '', // 分享描述
      link: '', // 分享链接
      imgUrl: '' // 分享图标
    },
    Bus: new Vue() // 非父子组件用来传递事件和接收事件
  },
  beforeCreate() {
    setTimeout(() => {
      let pf = performance.getEntries()[0] || {}
      $log({ e: $log.event.enter, p: { d: pf.domInteractive | 0, l: pf.duration | 0 }, ts: parseInt(performance.timeOrigin) })
    }, 1800);

    // 阻止冒泡的点击统计不到
    document.addEventListener('click', function (e) {
      let tg = e.target || e.currentTarget
      let param = {
        s: window.scrollY,
        x: e.pageX,
        y: e.pageY,
        t: tg.tagName || tg.nodeName,
        c: tg.className
      }
      // console.log('-----------', param, e)
      $log({ e: $log.event.click, p: param })
    })

    // 微信环境下引入微信jssdk
    if (/micromessenger/.test(window.navigator.userAgent.toLowerCase())) {
      var wxJsSdk = dom.createElement('script')
      wxJsSdk.id = '_wx_js_sdk'
      wxJsSdk.src = '//res.wx.qq.com/open/js/jweixin-1.2.0.js'
      dom.head.appendChild(wxJsSdk)
    }
    // const setVC = () => {
    //   // <script src="//files.eyee.com/mcdn/3rd/vconsole.min.js"> </script>
    //   let vcJs = dom.createElement('script')
    //   vcJs.src = 'https://files.eyee.com/mcdn/3rd/vconsole.min.js'
    //   vcJs.id = 'vconsole'
    //   vcJs.type = 'text/javascript'
    //   dom.head.appendChild(vcJs)
    //   vcJs.onload = () => {
    //     let vConsole = new VConsole()
    //     vcSeted = true
    //   }
    // }
    // if (ISDEBUG) setVC()
    // else {
    //   var vcSetTemp = 0
    //   var vcInterval = null
    //   var vcSeted = false
    //   dom.body.onclick = () => {
    //     if (vcSeted) return
    //     if (vcInterval) clearTimeout(vcInterval)
    //     vcSetTemp++
    //     // console.log('vcSetTemp', vcSetTemp)
    //     if (vcSetTemp === 11) setVC()
    //     vcInterval = setTimeout(() => { vcSetTemp = 0 }, 300)
    //   }
    // }

    if (DATA_REPORT) {
      // let appid = ISDEBUG ? 'DF8379746D014959A8B4A1B5AEBF8052' : 'BBD345EF46C9466588DA19ABFE8A7E0E' // 正式 BBD345EF46C9466588DA19ABFE8A7E0E
      // // TalkingData 注入
      // var tdJs = dom.createElement('script')
      // tdJs.src = `https://jic.talkingdata.com/app/h5/v1?appid=${appid}&vn=${process.env.NODE_ENV}&vc=${(Date.now() / 1000 / 60 / 60).toFixed()}`
      // dom.head.appendChild(tdJs)

      let gioJs = dom.createElement('script')
      gioJs.src = '//assets.growingio.com/2.1/gio.js'
      gioJs.async = 1
      gioJs.onload = function () {
        window.gio('init', 'b660df8bf4bd3488', { 'imp': false })
        window.gio('send')
      }
      gioJs.type = 'text/javascript'
      dom.head.appendChild(gioJs)

      let tdAdJs = dom.createElement('script')
      tdAdJs.src = 'https://h5.talkingdata.com/adt/h5sdk?ak=77D19F985CD24C9BA0833D41481D3D7E'
      tdAdJs.id = 'td_tracking_sdk'
      tdAdJs.type = 'text/javascript'
      dom.head.appendChild(tdAdJs)

      // let hmJs = dom.createElement('script')
      // hmJs.src = '//files.eyee.com/mcdn/3rd/hm.js?3172637ea5c928a8dbdfcace1fc4b2ee'
      // dom.head.appendChild(hmJs)

      // <script src="//files.eyee.com/mcdn/3rd/mta.js?v2.0.4" name="MTAH5" sid="500605722" cid="500605724"></script>
      // let mtaJs = dom.createElement('script')
      // mtaJs.src = '//files.eyee.com/mcdn/3rd/mta.js?v2.0.4'
      // mtaJs.setAttribute('name', 'MTAH5')
      // mtaJs.setAttribute('cid', '500605724')
      // mtaJs.setAttribute('sid', '500605722')
      // dom.head.appendChild(mtaJs)
    }

    // 2018-10-20 更新防刷工具，以下弃用
    // // 增加腾讯防刷组件 https://ssl.captcha.qq.com/TCaptcha.js
    // let tcJs = dom.createElement('script')
    // tcJs.src = 'https://ssl.captcha.qq.com/TCaptcha.js'
    // dom.head.appendChild(tcJs)
  },
  created() {
    // 组件创建完后获取数据，
    // 此时 data 已经被 observed 了
    this._initAgent()
  },
  methods: {
    _initAgent() {
      const _ = this
      let u = window.navigator.userAgent
      _.ISAPP = u.indexOf('platform/app') !== -1
      _.ISIOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/)
      _.ISWX = /micromessenger/.test(u.toLowerCase())
    },
    hideDownload() {
      this.downloadPage = false
    }
  }
})
